import { Client } from "minio";
import stream from "stream";

const minioClient = new Client({
  endPoint: "47.96.251.237",
  port: 9000,
  useSSL: false,
  accessKey: "ahct",
  secretKey: "ahct123456",
});
const bucketName = "ahctbucket";

export function toBlob(base64Data) {
  let byteString = base64Data;
  if (base64Data.split(",")[0].indexOf("base64") >= 0) {
    byteString = atob(base64Data.split(",")[1]);
  } else {
    byteString = unescape(base64Data.split(",")[1]);
  }
  const mimeString = base64Data.split(";")[0].split(":")[1];
  const uintArr = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
    uintArr[i] = byteString.charCodeAt(i);
  }
  return new Blob([uintArr], { type: mimeString });
}

export function uploadImage({ file, onSuccess, onError }) {
  const fileName = `${file.uid}-${file.name}`;
  const mimeType = file.type;
  const fileSize = file.size;
  const metadata = {
    "content-type": mimeType,
    "content-length": fileSize,
  };

  console.log("Starting uploadImage...");

  minioClient.bucketExists(bucketName, (err) => {
    if (err) {
      if (err.code === "NoSuchBucket") {
        console.log("Bucket不存在");
        onError(err);
        return;
      }
      console.error("Error checking bucket existence:", err);
      onError(err);
      return;
    }
    console.log("Bucket存在");
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onloadend = (e) => {
      const dataurl = e.target.result;
      const blob = toBlob(dataurl);
      const reader2 = new FileReader();
      reader2.readAsArrayBuffer(blob);
      reader2.onload = (ex) => {
        const bufferStream = new stream.PassThrough();
        bufferStream.end(Buffer.from(ex.target.result));
        minioClient.putObject(
          bucketName,
          fileName,
          bufferStream,
          fileSize,
          metadata,
          (err, etag) => {
            if (err) {
              console.error("Error uploading object:", err);
              onError(err);
              return;
            }
            console.log("Object uploaded successfully, etag:", etag);
            minioClient.presignedGetObject(
              bucketName,
              fileName,
              24 * 60 * 60,
              (err, presignedUrl) => {
                if (err) {
                  console.error("Error getting presigned URL:", err);
                  onError(err);
                  return;
                }
                console.log("Presigned URL:", presignedUrl);
                const fileData = { url: presignedUrl, name: fileName };
                onSuccess(fileData);
              }
            );
          }
        );
      };
    };
  });
}

export function removeObject(fileName, callback) {
  minioClient.removeObject(bucketName, fileName, (err) => {
    if (err) {
      console.error("删除对象时出错：", err);
    } else {
      console.log("对象已成功删除", bucketName, fileName);
      callback();
    }
  });
}
